<script setup>
import { ref, onBeforeMount } from 'vue'
import { ElMessage  } from 'element-plus'
import { updateNodeHandler } from '../../../api/node';
const props = defineProps({
    taintType: {
        type: String,
    },
    item: {
        type: Object
    },
    clusterId: {
        type: String
    },

})
const taint = ref(false)
onBeforeMount(() => {
    console.log("当前的污点类型和item数据：",props.taintType,props.item)
    // 判断是否已经配置了污点
    const taints = props.item.spec.taints
    if (taints != undefined) {
        for(let i=0;i<taints.length;i++) {
            const curtaint = taints[i]
            const effect = curtaint.effect
            const key = curtaint.key
            if (effect != props.taintType) {
                continue
            }
            if (key == 'node-role.kubernetes.io/master' ||
                key ==  'node-role.kubernetes.io/control-plane' ||
                key == 'node-role.kubernetes.io/controlplane') {
                    taint.value = true
                    break
            }
        }
    }

})
const updateTaint = () => {
    console.log("当前的值:",taint.value)
    //true:添加污点 false:删除污点
    if(taint.value) {
        const taints = props.item.spec.taints
        for(let i=0;i<taints.length;i++){
            const curTaint = taints[i]
            if (curTaint.effect == props.taintType) {
                if (curTaint.key == 'node-role.kubernetes.io/master' ||
                    curTaint.key ==  'node-role.kubernetes.io/control-plane' ||
                    curTaint.key == 'node-role.kubernetes.io/controlplane') {
                    props.item.spec.taints.splice(i, 1)
                }

            }
        }
        console.log("删除当前污点后的配置：",props.item.spec.taints)
    }else{
        const taint = {
            key: 'node-role.kubernetes.io/control-plane',
            effect: props.taintType
        }
        if(props.item.spec.taints == undefined) {
            props.item.spec.taints = []
        }
        props.item.spec.taints.push(taint)
        console.log("添加后的污点配置：",props.item.spec.taints)
    }
    // 更新节点状态
    return new Promise(async (resolve, reject) => {
        // 调用接口更新节点状态
        await updateNodeHandler(props.clusterId, props.item.metadata.name, props.item).then((res) => {
            if (res.data.status == 200) {
                ElMessage.success(res.data.message)
                return resolve(true)
            }else {
                ElMessage.error(res.data.message)
                return reject(false)
            }
        }).catch(
            err => {
                ElMessage.error(err.message)
                return reject(false)
            }
        )
    })
}
</script>
<template>
    <el-switch v-model="taint" :before-change="updateTaint"></el-switch>
</template>
<style scoped>
</style>